<?php
/**
 * Created by PhpStorm.
 * User: Mr.Li<LHB2002@qq.com>
 * Date: 2017-09-28
 * Time: 11:05
 */

namespace Resolution;


class Resolution
{
    private $config = array();
    /**
     * Resolution constructor.
     * @param $path         请求的图片路径
     * @param $style_name   请求图片样式
     * @param array $screen 当前请求的屏幕尺寸,用于响应式图片获取
     * @author Mr.Li<lhb2002@qq.com>
     */
    public function __construct($path , $style_name , $screen = array() )
    {
        try{
            $this->checkFile($path);
            $style = $this->loadStyle($style_name,$screen);

            $img = new ImageGD2($style);
            $img->setSourceImagePath($path);
            $img->setCacheImagePath($this->getCachePath($path , $style->style_name));

            $file = $img->generate();
            $this->response($file,$this->config['validity']);
        }
        catch (ResolutionException $exception){
            //todo 可以输出一张错误图片
            echo $exception->getMessage();
        }
    }

    /**
     * 通过名称，加载配置的参数信息
     * @param $style_name
     * @param array $screen
     * @author Mr.Li<lhb2002@qq.com>
     */
    private function loadStyle($style_name, $screen=array()){
        $config = require_once('config.php');

        if(!array_key_exists($style_name,$config['style'])){
            $style_name = $config['default_style'];
        }

        $this->config = $config['cache'];

        $style_data = $config['style'][$style_name];

        $style = new Style();
        $style->width       = $style_data['width'];
        $style->height      = $style_data['height'];
        $style->style_name = $style_name;
        $style->quality     = $style_data['quality'];
        $style->ignore      = $style_data['ignore'];
        if( $style_data['resolution'] ){
            $style->resolution = $style_data['resolution'];
            $style->setScreen($screen['width'],$screen['height']);
        }

        return $style;

    }

    /**
     * 检查源文件是否存在
     * @param $path
     * @return bool
     * @author Mr.Li<lhb2002@qq.com>
     */
    private function checkFile($path){
        if (!file_exists($path)) {
            header("Status: 404 Not Found");
            exit();
        }
        else{
            return true;
        }
    }

    /**
     * 检查保存目录是否存在并且可写入
     * @param $file
     * @return bool
     * @throws ResolutionException
     * @author Mr.Li<lhb2002@qq.com>
     */
    private function checkCacheDir($file){
        $cache_dir = dirname($file);
        if (!is_dir($cache_dir)) {
            if (!mkdir($cache_dir, 0755, true)) {
                if (!is_dir($cache_dir)) {
                    throw new ResolutionException('创建目录失败');
                }
            }
        }

        if (!is_writable($cache_dir)) {
            throw new ResolutionException('目录不具备文件写入权限');
        }
        return true;
    }

    /**
     * 获取缓存文件要保存的路径
     * @param $path
     * @param $style_name
     * @author Mr.Li<lhb2002@qq.com>
     */
    private function getCachePath($path , $style_name){
        $file = $this->config['path'] . $style_name . DIRECTORY_SEPARATOR . $path;

        $this->checkCacheDir($file);
        return $file;
    }

    /**
     * 输出指定图片文件
     * @param $filename
     * @param int $browser_cache
     * @author Mr.Li<lhb2002@qq.com>
     */
    private function response($filename, $browser_cache = 604800){
        $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        if (in_array($extension, array('png', 'gif', 'jpeg'))) {
            header("Content-Type: image/".$extension);
        } else {
            header("Content-Type: image/jpeg");
        }
        header("Cache-Control: private, max-age=".$browser_cache);
        header('Expires: '.gmdate('D, d M Y H:i:s', time()+$browser_cache).' GMT');
        header('Content-Length: '.filesize($filename));
        readfile($filename);
        exit();
    }



}